package com.cxyd.modules.wcs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cxyd.common.constant.Constants;
import com.cxyd.common.constant.WcsConstants;
import com.cxyd.common.page.PageData;
import com.cxyd.common.service.impl.CrudServiceImpl;
import com.cxyd.common.utils.ApiResult;
import com.cxyd.common.utils.ConvertUtils;
import com.cxyd.modules.log.service.SysLogWorkService;
import com.cxyd.modules.wcs.dao.AgvTrkHkDao;
import com.cxyd.modules.wcs.dao.AgvTrkYfDao;
import com.cxyd.modules.wcs.dao.PostWmsDao;
import com.cxyd.modules.wcs.dto.PostWmsDTO;
import com.cxyd.modules.wcs.entity.PostWmsEntity;
import com.cxyd.modules.wcs.entity.TrkEntity;
import com.cxyd.modules.wcs.service.PostWmsService;
import com.cxyd.modules.wcs.service.ReceiveTaskService;
import com.cxyd.modules.wcs.service.TrkService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import java.util.Map;

/**
 * 下发指令
 *
 * @author Cycle gengruyi01@163.com
 * @since 1.0.0 2022-11-04
 */
@Service
public class PostWmsServiceImpl extends CrudServiceImpl<PostWmsDao, PostWmsEntity, PostWmsDTO> implements PostWmsService {
    @Resource
    private TrkService trkService;
    @Resource
    private AgvTrkHkDao agvTrkHkDao;
    @Resource
    private AgvTrkYfDao agvTrkYfDao;
    @Resource
    private ReceiveTaskService receiveTaskService;
    @Resource
    private SysLogWorkService logWorkService;

    public PostWmsServiceImpl() {
    }

    @Override
    public PageData<PostWmsDTO> page(Map<String, Object> params) {
        IPage<PostWmsEntity> page = baseDao.selectPage(
                getPage(params, "update_date", false),
                getWrapper(params)
        );
        return getPageData(page, PostWmsDTO.class);
    }

    @Override
    public QueryWrapper<PostWmsEntity> getWrapper(Map<String, Object> params) {
        String contNo = (String) params.get("contNo");
        QueryWrapper<PostWmsEntity> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(contNo), "cont_no", contNo);
        return wrapper;
    }

    @Override
    public PostWmsDTO getPostWms() {
        QueryWrapper<PostWmsEntity> qw = new QueryWrapper<>();
        qw.lambda().eq(PostWmsEntity::getPostSt, 0)
                .isNotNull(PostWmsEntity::getRequestPk)
                .isNotNull(PostWmsEntity::getContNo)
                .orderBy(true, true, PostWmsEntity::getCreateDate)
                .last("limit 1");
        PostWmsEntity postWmsEntity = baseDao.selectOne(qw);
        return ConvertUtils.sourceToTarget(postWmsEntity, PostWmsDTO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void postWmsHandle(PostWmsDTO dto, ApiResult response) {
        String code = response.getCode();
        String msg = response.getMsg();
        String pCode = WcsConstants.PROC_CODE_SUCCESS;
        String pMsg = "容器[" + dto.getContNo() + "]到站点[" + dto.getCurPos() + "]并成功上报[MES],类型[" + dto.getNoticeType() + "]postId[" + dto.getPostId() + "]";
        int status;
        if (Constants.SUCCESS.equals(response.getCode())) {
            status = WcsConstants.POST_STATUS_SUCCESS;
//            成功下发更新[wcs_trk]任务状态
        } else {
            status = WcsConstants.POST_STATUS_ERROR;
            pCode = "postWmsHandle_001";
            pMsg = "容器[" + dto.getContNo() + "]搬送信号上报失败!causeBy:" + msg;
        }
//        开始时间-start
        Instant start = Instant.now();
//        1.更新post_wms记录状态
        PostWmsEntity postWmsEntity = baseDao.selectById(dto.getPostId());
//        核验类型是[通知]or[完成]
        postWmsEntity.setPostSt(status);
        postWmsEntity.setAckMsg(code + ":" + msg);
        postWmsEntity.setUpdater(WcsConstants.WCS_USER_ID);
        postWmsEntity.setUpdateDate(new Date());
        baseDao.updateById(postWmsEntity);
//        2.匹配对应的wcs_trk搬送任务
        TrkEntity wcsTrk = trkService.selectByContNo(dto.getContNo());
        if (wcsTrk == null) {
            return;
        }
//        任务上报成功则转移数据
        if (status == WcsConstants.POST_STATUS_SUCCESS) {
            baseDao.backupPostWms(dto.getContNo());
            baseDao.deleteById(dto.getPostId());
//            只有当通知类型为完成才会对任务进行转移
            if (WcsConstants.POST_TYPE_DONE.equals(dto.getNoticeType())) {
//        2.更新wcs_trk任务状态并转移(将同组的任务都进行转移)
                trkService.updateTrkByGroupNo(wcsTrk.getGroupNo());
//        3.指令信息转移
                receiveTaskService.updateReceiveTaskByContNo(dto.getContNo());
            }
        }
        //        结束时间-end
        Instant end = Instant.now();
        String workName = "[流程-POST]任务信息上报";
        String workProc = "PostWmsServiceImpl.postWmsHandle";
//        计算耗时
        Duration times = Duration.between(start, end);
        logWorkService.workLogging(workName, dto.getContNo(), pCode, pMsg, "", workProc, WcsConstants.WCS_USER_NAME, times.toMillis());
    }

    @Override
    public void updatePostWms(PostWmsEntity entity) {

    }
}